package com.ic.config;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.ic.common.DroolsContainer;
import com.ic.domain.Device;
import com.ic.domain.Rule;
import com.ic.service.DeviceService;
import com.ic.service.RuleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import static com.fasterxml.jackson.databind.MapperFeature.DEFAULT_VIEW_INCLUSION;

@Configuration
@Slf4j
public class GlobalConfig {
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private RuleService ruleService;
    @Autowired
    private DroolsContainer droolsContainer;

    @Bean
    public ClassPathResource initResource() {
        ClassPathResource resource = new ClassPathResource("data.json");
        initData(resource);
        return resource;
    }

    private void initData(ClassPathResource resource) {
        try (InputStream inputStream = resource.getInputStream()) {
            String json = IOUtils.toString(inputStream, "utf-8");
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
            // 设置FAIL_ON_UNKNOWN_PROPERTIES属性，当JSON字符串中存在Java对象没有的属性，忽略
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.configure(DEFAULT_VIEW_INCLUSION, false);

            JsonNode jsonNode = objectMapper.readTree(json);
            JsonNode dn = jsonNode.get("devices");

            List<Device> devices = objectMapper.readValue(dn.toString(), new TypeReference<List<Device>>() {
            });
            JsonNode rn = jsonNode.get("rules");
            List<Rule> rules = objectMapper.readValue(rn.toString(), new TypeReference<List<Rule>>() {
            });
            devices.forEach(deviceService::save);

            rules.forEach(ruleService::save);

            droolsContainer.checkAndUpdate("1");

            log.info("Json: {}", json);
        } catch (IOException e) {
            log.info("init data failed");
        }
    }

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true); // 允许cookies跨域
        config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI，*表示全部允许，在SpringMVC中，如果设成*，会自动转成当前请求头中的Origin
        config.addAllowedHeader("*");// #允许访问的头信息,*表示全部
        config.setMaxAge(18000L);// 预检请求的缓存时间（秒），即在这个时间段里，对于相同的跨域请求不会再预检了
        config.addAllowedMethod("*");// 允许提交请求的方法，*表示全部允许
        source.registerCorsConfiguration("/**", config);
        log.debug("cors filter init");
        return new CorsFilter(source);
    }
}
